var LocalStrategy = require('passport-local').Strategy,
  User = require('../app/model/user');

module.exports = function(passport, config, connection) {
  passport.serializeUser(function(user, done) {
    console.log("serializeUser");
    done(null, user.id);
  });

  passport.deserializeUser(function(id, done) {
    console.log("deserializeUser");
    var sql = "select u.*,e.name,e.state,e.email from user u left join employee e on u.employeeId= e.id where u.id=" + id;
    connection.query(sql, function(err, rows) {
      if (rows[0].name==null) {
        rows[0].name = "admin";
      }
      done(err, rows[0]);
    });
  });

  passport.use(new LocalStrategy(function(username, password, done) {
    console.log("LocalStrategy");
    User.findOne(connection, username, function(user) {
      if (!user[0]) {
        return done(null, false, {
          message: 'Incorrect username.'
        });
      }
      console.log("验证密码...");
      if (user[0].password != password) {
        return done(null, false, {
          message: 'Incorrect password.'
        });
      }
      return done(null, user[0]);
    });
  }));
};